package com.bj58.mis.apm.server.statistics.auth;

import com.bj58.mis.apm.server.statistics.common.LoginUser;
import com.bj58.mis.apm.server.statistics.common.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author: zhangfx
 * @create: 2018-07-04 10:39
 **/
public class AuthInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${roc.auth.basePackage}")
    private String baseAuthPackage;
    @Autowired
    protected RequestContext requestContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            Class controllerClass = method.getDeclaringClass();
            String packageName = controllerClass.getPackage().getName();
            if (!packageName.startsWith(baseAuthPackage)) {
                return true;
            }
            logger.debug("[AuthInterceptor] path={}", request.getServletPath());
            String userName = request.getParameter("roc_username");
            boolean isAdmin = "true".equalsIgnoreCase(request.getParameter("roc_isAdmin"));
            if (StringUtils.isNotEmpty(userName)) {
                requestContext.setLoginUser(new LoginUser(userName, isAdmin));
                return true;
            } else {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
        }
        return true;
    }
}
